package org.shj.jvm;

/**
 * -XX:+PrintGC -Xms50M -Xmx50M
 * @author Administrator
 *
 */
public class TestGC {
	
	private static int _6MB = 6 * 1024 * 1024;

	//变量a对应的内存未被 回收
	public void localVarGc1(){
		byte[] a = new byte[_6MB];
		System.gc();
	}
	
	//变量a对应的内存被回收
	public void localVarGc2(){
		byte[] a = new byte[_6MB];
		a = null;
		System.gc();
	}
	
	//变量a对应的内存未被 回收。原因：a仍然处于局部变量表中，
	//因此6MB的空间仍然存在有效引用
	public void localVarGc3(){
		{
			byte[] a = new byte[_6MB];//未被回收
		}
		System.gc();
	}
	
	//变量a对应的内存被 回收。原因：变量a已失效，变量c取代了a在局部变量表中
	//的位置，因此6MB的空间不存在有效引用
	public void localVarGc4(){
		{
			byte[] a = new byte[_6MB];//被回收
		}
		int c = 10;
		System.gc();
	}
	
	//localVarGc1()调用完后，它的栈帧被销毁了，因此byte数组
	//失去引用，被localVarGc5()中的System.gc()回收掉
	public void localVarGc5(){
		localVarGc1();
		System.gc();
	}
	
	public static void main(String[] args) {
		TestGC test = new TestGC();
		System.out.println("======= localVarGc1() ========");
		test.localVarGc1();
		System.out.println("======= localVarGc2() ========");
		test.localVarGc2();
		System.out.println("======= localVarGc3() ========");
		test.localVarGc3();
		System.out.println("======= localVarGc4() ========");
		test.localVarGc4();
		System.out.println("======= localVarGc5() ========");
		test.localVarGc5();
	}
}
